#include "../include/client.h"
#define MAX_SIZE (25000*4096)

int recvn(int sockfd, void *buf, int length){
    char *pbuf = (char *)buf;
    int cursize = 0;
    while(cursize < length){
        ssize_t sret = recv(sockfd,pbuf + cursize,length - cursize,0);
        cursize += sret;
        if(sret == 0){
            break;
        }
    }
    return 0;
}

//正式接收时使用小火车：buf = train.data，*flag = &train.flag
int recvFile(int sockfd,char* buf,int *flag){
    train_t train ;
    recvn(sockfd,&train.flag,sizeof(train.flag));
    recvn(sockfd,&train.length,sizeof(train.length));
    recvn(sockfd,train.data,train.length);
    char filename[4096] = {0};
    memcpy(filename,train.data,train.length);
    printf("filename = %s\n",filename);
    memcpy(filename,buf,strlen(buf));
    int filefd=open(filename,O_RDWR|O_CREAT|O_TRUNC,0666);
    if(filefd == -1){
        printf("打开文件失败!\n");
        return -1;                
    }
    off_t filesize;//定义变量存储文件总大小
    recvn(sockfd,&train.flag,sizeof(train.flag));
    recvn(sockfd,&train.length,sizeof(train.length));
    recvn(sockfd,train.data,train.length);
    memcpy(&filesize,train.data,sizeof(off_t));//将接收到的文件大小数据转换为off_t类型
    printf("filesize = %ld\n",filesize);
    while(1){//循环接收文件数据块并写入文件
        bzero(train.data,sizeof(train.data));
        recvn(sockfd,&train.flag,sizeof(train.flag));
        recvn(sockfd,&train.length,sizeof(train.length));
        if(train.length!=4096){
            printf("train.length = %d\n",train.length);
        }
        recvn(sockfd,train.data,train.length);
        if(train.length==0){
            break;
        }
        write(filefd,train.data,train.length);//将数据块写入文件
    }
    close(filefd);
    return 0;
}

